package com.cjk.service.Impl;

import com.cjk.mapper.EmpExprMapper;
import com.cjk.mapper.EmpLogMapper;
import com.cjk.mapper.EmpMapper;
import com.cjk.pojo.*;
import com.cjk.service.EmpService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmpServiceImpl implements EmpService {

    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private EmpExprMapper empExprMapper;
    @Autowired
    private EmpLogMapper empLogMapper;
    @Override
    public PageResult<Emp> page(EmpPageHelper empPageHelper) {
        PageHelper.startPage(empPageHelper.getPage(), empPageHelper.getPageSize());
        List<Emp> empList = empMapper.page(empPageHelper);

        Page<Emp> empPage = (Page<Emp>) empList;

        return new PageResult<Emp>(empPage.getTotal(), empPage.getResult());
    }

    /**
     * 添加员工
     * @param emp
     */
    @Transactional
    @Override
    public void add(Emp emp) {
        try {
            emp.setCreateTime(LocalDateTime.now());
            emp.setUpdateTime(LocalDateTime.now());
            empMapper.add(emp);

            Integer empId = emp.getId();
            List<EmpExpr> exprList = emp.getExprList();
            if (!CollectionUtils.isEmpty(exprList)) {
                exprList.forEach(empExpr -> empExpr.setEmpId(empId));
                empExprMapper.insertBatch(exprList);


            }
        }finally {
            EmpLog empLog = new EmpLog(null, LocalDateTime.now(), "添加员工：" + emp);
            empLogMapper.insert(empLog);
        }
    }

    /**
     * 批量删除员工
     * @param ids
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteBatch(Integer[] ids) {
        empMapper.deleteBatch(ids);
        empExprMapper.deleteBatch(ids);

    }

    /**
     * 根据id查询员工
     * @param id
     * @return
     */
    @Override
    public Emp findById(Integer id) {
        return empMapper.findById(id);

    }

    /**
     * 修改员工信息
     * @param emp
     */
    @Transactional
    @Override
    public void update(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.update(emp);

        empExprMapper.deleteBatch(new Integer[] {emp.getId()});

        List<EmpExpr> exprList = emp.getExprList();
        if (!CollectionUtils.isEmpty(exprList)) {
            exprList.forEach(empExpr->empExpr.setEmpId(emp.getId()));
            empExprMapper.insertBatch(exprList);
        }

    }

//    /**
//     * 查询班主任
//     * @return
//     */
//    @Override
//    public List<Emp> list() {
//        return empMapper.list();
//    }
}
